#!/usr/bin/env python3
"""
创建测试视频
用于测试视频分析系统
"""

import cv2
import numpy as np
import os
from pathlib import Path

def create_test_video(output_path="test_video.mp4", duration=10, fps=30):
    """
    创建一个简单的测试视频
    
    Args:
        output_path: 输出视频路径
        duration: 视频时长（秒）
        fps: 帧率
    """
    
    # 视频参数
    width, height = 640, 480
    total_frames = duration * fps
    
    # 创建视频写入器
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    print(f"创建测试视频: {output_path}")
    print(f"分辨率: {width}x{height}, 时长: {duration}秒, 帧率: {fps}fps")
    
    for frame_num in range(total_frames):
        # 创建空白帧
        frame = np.zeros((height, width, 3), dtype=np.uint8)
        
        # 添加背景色（渐变）
        frame[:, :, 0] = int(50 + 50 * np.sin(frame_num * 0.1))  # Blue
        frame[:, :, 1] = int(100 + 50 * np.cos(frame_num * 0.1))  # Green
        frame[:, :, 2] = int(150 + 50 * np.sin(frame_num * 0.05))  # Red
        
        # 添加移动的圆形（模拟人物）
        center_x = int(width * 0.2 + (width * 0.6) * (frame_num / total_frames))
        center_y = int(height * 0.5 + 50 * np.sin(frame_num * 0.2))
        
        # 绘制"人物"（红色圆形）
        cv2.circle(frame, (center_x, center_y), 30, (0, 0, 255), -1)
        
        # 添加文本
        current_second = frame_num // fps
        text = f"Time: {current_second}s"
        cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
        
        # 在特定时间段添加"目标"
        if 3 <= current_second <= 7:
            # 绘制"目标物体"（绿色矩形）
            target_x = int(width * 0.7)
            target_y = int(height * 0.3)
            cv2.rectangle(frame, (target_x-40, target_y-30), (target_x+40, target_y+30), (0, 255, 0), -1)
            cv2.putText(frame, "TARGET", (target_x-35, target_y+5), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
        
        # 写入帧
        out.write(frame)
        
        # 显示进度
        if frame_num % (fps * 2) == 0:  # 每2秒显示一次进度
            progress = (frame_num / total_frames) * 100
            print(f"进度: {progress:.1f}%")
    
    # 释放资源
    out.release()
    print(f"✅ 测试视频创建完成: {output_path}")

def create_multiple_test_videos():
    """创建多个不同类型的测试视频"""
    
    # 创建测试视频目录
    test_dir = Path("test_videos")
    test_dir.mkdir(exist_ok=True)
    
    # 视频1: 简单移动目标
    print("\n1. 创建简单移动目标视频...")
    create_test_video(
        output_path=str(test_dir / "simple_target.mp4"),
        duration=8,
        fps=25
    )
    
    # 视频2: 复杂场景
    print("\n2. 创建复杂场景视频...")
    create_complex_video(
        output_path=str(test_dir / "complex_scene.mp4"),
        duration=12,
        fps=30
    )
    
    print(f"\n✅ 所有测试视频已创建在 {test_dir} 目录中")

def create_complex_video(output_path="complex_scene.mp4", duration=12, fps=30):
    """创建复杂场景的测试视频"""
    
    width, height = 800, 600
    total_frames = duration * fps
    
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    for frame_num in range(total_frames):
        # 创建渐变背景
        frame = np.zeros((height, width, 3), dtype=np.uint8)
        
        # 添加渐变背景
        for y in range(height):
            for x in range(width):
                frame[y, x] = [
                    int(100 + 100 * (x / width)),
                    int(50 + 150 * (y / height)),
                    int(200 - 100 * (x / width))
                ]
        
        current_second = frame_num // fps
        
        # 添加多个移动对象
        # 对象1: 红色圆形（人物）
        person_x = int(100 + 600 * (frame_num / total_frames))
        person_y = int(300 + 100 * np.sin(frame_num * 0.1))
        cv2.circle(frame, (person_x, person_y), 25, (0, 0, 255), -1)
        
        # 对象2: 蓝色矩形（车辆）
        if current_second >= 2:
            car_x = int(width - 50 - 500 * ((frame_num - 2*fps) / total_frames))
            car_y = int(height - 100)
            cv2.rectangle(frame, (car_x-40, car_y-20), (car_x+40, car_y+20), (255, 0, 0), -1)
        
        # 对象3: 绿色三角形（特殊目标）
        if 4 <= current_second <= 8:
            target_x = int(400 + 200 * np.cos(frame_num * 0.05))
            target_y = int(200 + 100 * np.sin(frame_num * 0.08))
            points = np.array([
                [target_x, target_y-30],
                [target_x-25, target_y+20],
                [target_x+25, target_y+20]
            ], np.int32)
            cv2.fillPoly(frame, [points], (0, 255, 0))
        
        # 添加时间戳
        cv2.putText(frame, f"Time: {current_second}s", (10, 30), 
                   cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
        
        # 添加场景描述
        if current_second < 2:
            cv2.putText(frame, "Scene: Person walking", (10, height-20), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        elif current_second < 4:
            cv2.putText(frame, "Scene: Person + Car", (10, height-20), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        elif current_second < 8:
            cv2.putText(frame, "Scene: Multiple objects", (10, height-20), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        else:
            cv2.putText(frame, "Scene: Person + Car", (10, height-20), 
                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
        
        out.write(frame)
    
    out.release()

if __name__ == "__main__":
    print("🎬 测试视频生成器")
    print("=" * 30)
    
    # 检查OpenCV
    print(f"OpenCV版本: {cv2.__version__}")
    
    # 创建测试视频
    create_multiple_test_videos()
    
    print("\n📝 测试建议:")
    print("1. 使用 'person' 或 'red circle' 搜索简单目标视频中的人物")
    print("2. 使用 'green triangle' 搜索复杂场景视频中的特殊目标")
    print("3. 使用 'blue rectangle' 或 'car' 搜索车辆")
    print("4. 尝试搜索不存在的目标，如 'cat' 或 'tree'")
    
    print("\n🚀 现在可以启动系统进行测试:")
    print("   ./start.sh")
    print("   或")
    print("   ./start-docker.sh")
